/**
 * Created by fengchong on 2017/7/5.
 */


//------------播放相关------------
var imgWidth = 500;
var imgHeight = 333;
var currentZoom = 1.0;

//这里应该变成47.93.18.177这个地址
// var dataServiceURL = "http://115.28.152.87:8080/image/user/";
var dataServiceURL = "http://47.93.18.177/image/user/"
var imageServiceURL = "http://115.28.152.87/img-server/uploads/";

var imgObjects = [];                                                                                                //保存用户的图片对象
var imgList = [];                                                                                                   //保存用户的访问图片url

var sound = new Audio();
// var canvas; = document.getElementById("canvasBox");
var canvas, ctx;
// var ctx; = canvas.getContext('2d');

function init(userid) {

    //获得配置数据
    var lang = getQueryString('lang');
    if (custId) {
        $('#links').attr('src', "https://my.matterportvr.cn/show/?m=" + custId + "&play=1&lang=" + lang + "&qs=1");

        //获得访客数与转发数
        $.getJSON("http://47.93.18.177:8081/data/statistics/query?mp_id=" + custId,function(result){

            $.each(result, function (idx, result) {
                var zhuaf = result.share_friend_count + result.share_timeline_count;
                var str = ' 访客数<span class="forward">' + result.view_count + '</span>&nbsp;&nbsp;&nbsp;&nbsp;转发数<span class="preview">' + zhuaf + '</span>';
                $('.top_lite').append(str);
            })
        });

        //获得一些活动信息等内容
        $.getJSON("http://47.93.18.177:8081/mp/query?mp_id=" + custId,function(result){
            console.log(result)
            $.each(result, function (idx, result) {
                console.log(result.activity_info)
                window.sessionStorage.setItem('name', result.activity_info);
                window.sessionStorage.setItem('img_hund', result.propaganda);
                window.sessionStorage.setItem('address', result.address);
                //活动页面、报价展示、官网首页等处理
                var str = ' <p class="activity" onclick="tanchu(1)"><a>活动信息</a></p><p class="activity"><a href="' + result.activity_page + '">活动页面</a></p><p class="activity"><a href="' + result.price_show + '">报价展示</a></p> <p class="activity"><a href="' + result.official_website + '">官网首页</a></p>';
                if (result.activity_info == "-")
                    str = '<p class="activity"><a href="' + result.activity_page + '">活动页面</a></p><p class="activity"><a href="' + result.price_show + '">报价展示</a></p> <p class="activity"><a href="' + result.official_website + '">官网首页</a></p>';
                $('.box_Packing').append(str);

                //开屏首页设置
                if (result.propaganda != "-" && result.propaganda_switch != false)
                    tanchu(2);

                //电话号码设置
                $('#a_tel').attr('href','tel:'+result.phone);

                //音乐设置
                sound.src = result.bgm;
                sound.play();
                wxParamsInit(location.href.split('#')[0],custId, result.share_title, result.share_desc, location.href.split('#')[0], result.share_icon);
            })
        });

    } else {
        if (!lang) {
            $('#links').attr('src', "https://my.matterportvr.cn/show/?m=zq7JmhfUtJU&play=1&lang=" + lang + "&qs=1");
        }
        sound.play();
    }



    //统计数据
    $.get("http://47.93.18.177:8081/data/statistics/submit?mp_id=" + userid + "&type=viewcount", function (data) {});
}

function requestUserData(userid, body) {
    $.getJSON(dataServiceURL + userid, function (result) {

        $.each(result.images, function (i, field) {
            imgList.push(imageServiceURL + field);
        });

//        $("#content").height($(document).height());
        canvas.width = body.width();
        canvas.height = (body.width() / imgWidth) * imgHeight;

        //获得图片对象
        getImageObjects(imgList);

    }).fail(function () {
        alert("请求数据失败");
    });
}


var loadcount = 0;
//根据访问地址，获得图片对象
function getImageObjects(ilist) {
    for (var i = 0; i < ilist.length; i++) {
        var img = new Image();
        img.src = ilist[i];
        img.onload = function () {
            setShareImgUrl(this.src);

            loadcount++;
            imgObjects.push(this);
            //当加载完最后一个图片。对已有的图片进行排序
            if (imgObjects.length == imgList.length) {
                sortImgObjects();
                setInterval(handleTick, 150);
            } else {
//                    console.info("loadcount:"+loadcount+"  length:"+ilist.length);
                var num = parseInt((loadcount / ilist.length) * 100);
                displayText(num + "%");
            }
        }
    }
}


var imgIndex = 0;
var indexDirect = true;                                                                                             //当方向为true时为加，方向为false时为减
//由setInterval持有
function handleTick() {
//        console.info("handleTick");

    //图片索引从头-》尾——》头。。。。。
    if (imgIndex < imgObjects.length - 1 && indexDirect == true) {
        imgIndex++;
        //当索引到最后时，索引操作方向取反
        if (imgIndex >= imgObjects.length - 1)
            indexDirect = !indexDirect;
    }
    else if (imgIndex > 0 && indexDirect == false) {
        imgIndex--;
        //当索引到第一张时，索引操作方向取反
        if (imgIndex <= 0)
            indexDirect = !indexDirect;
    }

    if (imgObjects[imgIndex] != null)
        displayImage(imgObjects[imgIndex]);
}

//加载完毕，绘制图片
function displayImage(img) {
    var docWidth = $("body").width();
    var docHeight = $(document).height();
    ctx.clearRect(0, 0, docWidth, docHeight);

    var newHeight = (docWidth / imgWidth) * imgHeight;
    var imgTop = 0;
    var imgLeft = ( (docWidth / 2) - (docWidth / 2) * currentZoom );
    ctx.drawImage(img, imgLeft, imgTop, docWidth * currentZoom, newHeight * currentZoom);

}

//显示百分比文字
function displayText(num) {
    console.info("displayText:" + num);
    var docWidth = $("body").width();
    var docHeight = $(document).height();

    ctx.clearRect(0, 0, docWidth, docHeight);
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle';
    ctx.fillStyle = 'white';
    ctx.font = "40px '微软雅黑'";
//        ctx.fillText(num,docWidth/2,docHeight/2);
    ctx.fillText(num, docWidth / 2, ctx.canvas.height / 2);
}

//对imgObjects进行排序
function sortImgObjects() {
    var tmpimg = new Array(imgObjects.length);
    for (var i = 1; i <= imgObjects.length; i++) {
        var name = imgObjects[i - 1].src;
        var nameindex = name.split("_")[1].split(".")[0];
        tmpimg[nameindex - 1] = imgObjects[i - 1];
    }

    imgObjects = tmpimg;
}
//------------播放相关------------

//-------------微信相关------------

var wechatUrl = "http://47.93.18.177/share/wechat";                                                                     //请求微信各参数的地址
var appid = '';
var timestamp = '';
var nonceStr = '';
var signature = '';

function wxParamsInit(param_url,userid,title,desc,link,imgUrl){
    //数据统计地址
    // var statisticsUrl = "http://meijiabao.cc/data/statistics";
    var statisticsUrl = "http://47.93.18.177:8081/data/statistics/submit";
    //分享给朋友
    shareAppMessageData = makeShareData(title, desc, link, imgUrl, function (res) {
        $.get(statisticsUrl + "?mp_id=" + userid + "&type=friend", function () {
        });
        console.info("statistics friend:" + imgUrl);
    });
    //分享到QQ
    shareQQData = makeShareData(title, desc, link, imgUrl, function (res) {
        $.get(statisticsUrl + "?mp_id=" + userid + "&type=qq", function () {
        });
        console.info("statistics qq:" + imgUrl);
    });
    //分享到微博
    shareWeiBoData = makeShareData(title, desc, link, imgUrl, function (res) {
        $.get(statisticsUrl + "?mp_id=" + userid + "&type=weibo", function () {
        });
        console.info("statistics weibo:" + imgUrl);
    });
    //分享到朋友圈
    shareTimeLineData = makeShareData(title, desc, link, imgUrl, function (res) {
        $.get(statisticsUrl + "?mp_id=" + userid + "&type=timeline", function () {
        });
        console.info("statistics timeline:" + imgUrl)
    });

    wxConfig(param_url);
    wxready(wx);
}

function wxConfig(param_url) {

//此处请求签名的url需要动态带入，不能写成固定的。
//现在抛出invalid url domain错误，怀疑安全域名应该填成www.homeetvr.com

    $.get(wechatUrl + '?url=' + encodeURIComponent(param_url), function (result) {
        console.log(param_url)
        console.log(result)
        var json = JSON.parse(result);
        appid = json.appid;
        timestamp = json.timestamp;
        nonceStr = json.nonceStr;
        signature = json.signature;
        wx.config({
            debug: false,
            appId: appid,
            timestamp: timestamp,
            nonceStr: nonceStr,
            signature: signature,
            jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline', 'onMenuShareQQ', 'onMenuShareWeibo']
        });

    });
}

var shareAppMessageData = {}, shareQQData = {}, shareWeiBoData = {}, shareTimeLineData = {};
/**
 * 用来设置各种共享函数的配置数据
 * @param wx        微信对象
 * @param userid    用户的id
 * @param title     共享数据的标题
 * @param desc      共享数据的详情
 * @param link      共享数据的源连接
 * @param imgUrl    共享数据的图标
 */
function wxready(wx) {
    wx.ready(function () {
        //分享给朋友
        wx.onMenuShareAppMessage(shareAppMessageData);
        //分享到QQ
        wx.onMenuShareQQ(shareQQData);
        //分享到微博
        wx.onMenuShareWeibo(shareWeiBoData);
        //分享到朋友圈
        wx.onMenuShareTimeline(shareTimeLineData);
    });


}
/**
 * 生成共享数据
 * @param title     共享数据的标题
 * @param desc      共享数据的详情
 * @param link      共享数据的源连接
 * @param imgUrl    共享数据的图标
 * @param sucfun    共享成功后的函数
 * @returns {{title: string, desc: string, link: *, imgUrl: *, success: *, fail: fail}}
 */
function makeShareData(title, desc, link, imgUrl, sucfun) {
    var shareData = {
        title: title,
        desc: desc,
        link: link,
        imgUrl: imgUrl,
        success: sucfun,
        fail: function (res) {
        }
    };
    return shareData;
}


/**
 * 设置所有共享数据的图标的url
 * @param src
 */
function setShareImgUrl(src) {
    // console.info("src:"+src);
    if ("imgUrl" in shareAppMessageData) shareAppMessageData.imgUrl = src;
    if ("imgUrl" in shareQQData) shareQQData.imgUrl = src;
    if ("imgUrl" in shareWeiBoData) shareWeiBoData.imgUrl = src;
    if ("imgUrl" in shareTimeLineData) shareTimeLineData.imgUrl = src;
}

function wxInit() {

}
//-------------微信相关------------

//------------音乐相关------------

//音乐新代码.设置默认bgm
sound.src="http://115.28.85.67/static.resources/bgm_sjfk.mp3";
function switch_bgm(){
    if(sound.paused){
        sound.play();
        $('#bgm_img').attr('src','images/sound_close.png');
    } else if(!sound.paused){
        sound.pause();
        $('#bgm_img').attr('src','images/sound_open.png');
    }
}


//------------音乐相关------------

//------------评论相关------------
//mp全屏
function open_quanp() {
     if ($('.mp_kuo').css('visibility') == 'visible') {
     $('.mp_kuo').css({'background':'url(./images/quanp_a.png) '})
     $('.mp_kuo').css({'background-size':'100% 100% '})
     $('.mp_kuo').css({'visibility':'inherit'})
     $('.top_lite').hide()
     $('.box_Packing').hide()
     $('#box_ioc').hide()
     return false
     } else {
     alert("xsax")
     $('.mp_kuo').css({'background':'url(./images/quanp_b.png) '})
     $('.mp_kuo').css({'background-size':'100% 100% '})
     $('.top_lite').show()
     $('.box_Packing').show()
     $('.box_ioc').show()
     }


}
/**
 * 打开或关闭录入评论的对话框
 */
function open_comment() {
    if ($('#cm_input').css('visibility') == 'visible') {
        $('#cm_input').css("visibility", "hidden");
        $('#cm_submit').css("visibility", "hidden");
        $('#cm_open').attr('class', 'hidden');
        $.fn.barrager.removeAll();
    }
    else {
        $('#cm_input').css("visibility", "visible");
        $('#cm_submit').css("visibility", "visible");
        $('#cm_open').attr('class', 'visible');
    }
    event.stopPropagation();
    tanchu(3)
}

var submitCommentUrl = "http://47.93.18.177:8081/comment/submit";
/**
 * 提交弹幕评论
 */
function submit_comment(mp_id, comment) {
    // 弹幕内容为空，不能提交
    if (!comment) return false;
    comment.replace("\n","");
    comment.replace("\r","");

    $.get(submitCommentUrl + "?mp_id=" + mp_id + "&comment=" + comment, function (result) {
        var json = JSON.parse(result);
        if (json.insert_count > 0) {
            //操作成功后，清空输入框，飞出刚刚发送的弹幕
            document.getElementById('cm_input').childNodes[0].nodeValue = '';
            var item = {
                info: comment,
                href:'http://www.homeetvr.com',
                close: true,
                speed: 15,
                color: '#ffd200',
                old_ie_color: '#000000'
            }
            $('body').barrager(item);
        } else {
            alert("发送弹幕失败！请重试。");
        }
    });
}

var queryCommentUrl = "http://47.93.18.177:8081/comment/query";
/**
 * 查看已有的弹幕
 */
function query_comment(mp_id) {
    var items = new Array();
    $.get(queryCommentUrl + "?mp_id=" + mp_id, function (result) {
        $.each(JSON.parse(result), function (i, field) {
            var item = {
                info: field.comment, //文字
                href: 'http://www.homeetvr.com',    //链接
                close: true,                        //显示关闭按钮
                speed: 15,                          //延迟,单位秒,默认6
                color: '#fff',                      //颜色,默认白色
                old_ie_color: '#000000',            //ie低版兼容色,不能与网页背景相同,默认黑色
            }
            items.push(item);
        });

        //如果弹幕数量小于1，直接返回
        if(items.length<=0) return;

        var looper_time = 3 * 1000;                                                                                     //每条弹幕发送间隔
        var total = items.length;
        var run_once = true;                                                                                            //首次执行
        var index = 0;                                                                                                  //弹幕索引

        barrager();                                                                                                     //执行一次，初始化计时器
        function barrager() {
            if (run_once) {
                //如果是首次执行,则设置一个定时器,并且把首次执行置为false
                looper = setInterval(barrager, looper_time);
                run_once = false;
            }
            //发布一个弹幕

            $('body').barrager(items[index]);
            //索引自增
            index++;
            //弹幕发布完毕，清除计时器。
            if (index == total) {
                index=0;
                // clearInterval(looper);
                // return false;
            }
        }
    });

    //此处用来处理iOS遮挡输入框的问题
    setInterval(function () {
        document.body.scrollTop = document.body.scrollHeight
    }, 300);
}
/*取链接中的参数*/
function getQueryString(name){
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = (window.location.href.indexOf('?') > -1) && window.location.href.split('?')[1].match(reg);
    if (r) {
        return unescape(r[2]);
    }
    return null;
}
//------------评论相关------------

//------------其他----------------
$(".close_img").click(function () {
    $('.mengc').hide()
    $('.popup-overlay').hide()
});

function tanchu(data) {
    if (data == "2") {
        $('#if_gai').attr('src', "list/img.html");
    } else if (data == "1") {
        $('#if_gai').attr('src', "list/huod.html");
    } else if (data == "3") {
        $('#if_gai').attr('src', "list/commen.html?fort=" + custId);
    } else {
        $('#if_gai').attr('src', "list/baidu_map.html");
    }
    $('.mengc').show()
    $('.popup-overlay').show()
}
//------------其他----------------
























